package com.whately.core.base.utils;


import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Base64Utils;

public class DES3Util {

          /**
    * @param content
    * @param desKey 3DES KEY
    * @return
    * @throws Exception
    */
          public static String encrypt(String content, String desKey) {
              String str = null;
              try {
                  if(StringUtils.isEmpty(desKey) || desKey.length() != 24) {
                      throw new Exception("3des key's length must be 24");
                  }
                  if(StringUtils.isEmpty(content)) {
                      return "";
                  }

                  SecretKeySpec key = new SecretKeySpec(desKey.getBytes("utf-8"), "DESede");
                  Cipher cipher = Cipher.getInstance("DESede");
                  cipher.init(Cipher.ENCRYPT_MODE, key);
                  byte [] encryptBytes = cipher.doFinal(content.getBytes("utf-8"));
                  str = Base64Utils.encodeToUrlSafeString(encryptBytes);
              } catch (Exception e) {
                  e.printStackTrace();
              }
              return str;
          }

          /**
    * @param content
    * @param desKey  3des key
    * @return
    * @throws Exception
    */
          public static String decrypt(String content, String desKey)throws Exception {
              try {
                  if(StringUtils.isEmpty(desKey) || desKey.length() != 24) {
                      throw new Exception("3des key's length must be 24");
                  }
                  if(StringUtils.isEmpty(content)) {
                      return "";
                  }

                  byte [] decryptBytes = null;
                  decryptBytes = Base64Utils.decodeFromUrlSafeString(content);

                  SecretKeySpec key = new SecretKeySpec(desKey.getBytes("utf-8"), "DESede");
                  Cipher cipher = Cipher.getInstance("DESede");
                  cipher.init(Cipher.DECRYPT_MODE, key);

                  return new String(cipher.doFinal(decryptBytes), "utf-8");
              } catch (Exception e) {
                  throw e;
              }
          }

          public static void main(String[] args) throws Exception {
              String key = "F6011F0398F3461BA53D3A9B";
              String content = "5198633";
              String jiami = DES3Util.encrypt(content, key);
              System.out.println("jiami = " + jiami);
              String jiemi = DES3Util.decrypt(jiami, key);
              System.out.println("jiemi = " + jiemi);
          }
        }
